package com.li.utilstest

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.media.MediaRecorder
import android.media.MediaScannerConnection
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.util.Log
import androidx.annotation.RequiresApi
import java.io.File
import java.io.IOException


/**
 * @author : liyun
 * @ClassName: MediaRecordScreenService
 * @Package com.li.utilstest
 * @Description:
 * @company: 深圳君南信息系统有限公司
 * @date 2021/8/22 21:35
 * @version v1.0
 */
class MediaRecordScreenService: BaseService() {
    companion object {
        val STOP = 1008
        val START = 1007
        val KEY = "key"
    }

    private var mediaRecorder: MediaRecorder? = null
    private var width = 0
    private var height = 0
    var virtualDisplay: VirtualDisplay? = null
    private var recordFile: File? = null
    private var mediaProjection: MediaProjection? = null

    // onStartCommand
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun initData(intent: Intent?, flags: Int, startId: Int) {
        val key = intent?.getIntExtra(KEY, -1)
        when(key){
            START ->{
                val resultCode = intent?.getIntExtra("resultCode", -1)
                width = intent?.getIntExtra("width", -1)!!
                height = intent?.getIntExtra("height", -1)
                val data = intent.getParcelableExtra<Intent>("data")
                val mediaProjectionManager =
                    getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
                val mediaProjection = mediaProjectionManager.getMediaProjection(
                    resultCode!!,
                    data!!
                )

                if(mediaProjection != null) {
                    // 获取存储的位置
                    recordFile = getExternalFilesDir("RecordFile")
                    val mkdirs = recordFile!!.mkdirs()
                    initMediaRecorder()
                    /**
                     * 创建投影
                     * name 本次虚拟显示的名称
                     * width 录制后视频的宽
                     * height 录制后视频的高
                     * dpi 显示屏像素
                     * flags VIRTUAL_DISPLAY_FLAG_PUBLIC 通用显示屏
                     * Surface 输出位置
                     */
                    virtualDisplay = mediaProjection.createVirtualDisplay(
                        "record-video", width, height, 6000000,
                        DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC, mediaRecorder?.surface, null, null
                    )
                    mediaRecorder?.start()
                }
            }
            STOP -> {
                stopSelf()
            }
        }

    }

    // onCreate
    override fun initCreate() {

    }

    /**
     * 初始化MediaRecorder
     *
     * @return
     */
    private fun initMediaRecorder() {
        mediaRecorder = MediaRecorder()
        mediaRecorder?.apply {
            // 设置音频来源
            mediaRecorder!!.setAudioSource(MediaRecorder.AudioSource.MIC)
            // 设置视频来源
            mediaRecorder!!.setVideoSource(MediaRecorder.VideoSource.SURFACE)
            // 设置输出格式
            mediaRecorder!!.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
            // 设置输出文件
            val absolutePath = File(recordFile.toString() + "/record.mp4").absolutePath
            Log.e("PATH", absolutePath)
            mediaRecorder!!.setOutputFile(absolutePath)
            // 设置视频宽高
            mediaRecorder!!.setVideoSize(width, height)
            // 设置视频帧率
            mediaRecorder!!.setVideoFrameRate(60)
            // 设置视频编码比特率
            mediaRecorder!!.setVideoEncodingBitRate(6000000)
            // 设置音频编码
            mediaRecorder!!.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
            // 设置视频编码
            mediaRecorder!!.setVideoEncoder(MediaRecorder.VideoEncoder.H264)
            try {
                mediaRecorder!!.prepare()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    fun release() {
        if (virtualDisplay != null) {
            virtualDisplay?.release()
            virtualDisplay = null
        }
        if (mediaRecorder != null) {
            mediaRecorder?.setOnErrorListener(null)
            mediaProjection?.stop()
            mediaRecorder?.reset()
            mediaRecorder?.release()
        }
        mediaProjection?.stop()
        scanVideo()
    }

    fun scanVideo(){
        //是否添加到相册
        val localContentResolver = this.contentResolver
        val localContentValues: ContentValues =
            getVideoContentValues( File(recordFile.toString() + "/record.mp4"), System.currentTimeMillis())
        val localUri: Uri? = localContentResolver.insert(
            MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
            localContentValues
        )
        var intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
        intent.data = localUri
        sendBroadcast(intent)
    }

    fun getVideoContentValues( file: File, long:Long): ContentValues{
        var values = ContentValues()
        values.put("title", file.name)
        values.put("_display_name", file.name)
        values.put("mime_type", "video/mp4")
        values.put("datetaken", long)
        values.put("date_modified", long)
        values.put("date_added", long)
        values.put("_data", file.absolutePath)
        values.put("_size", file.length())
        return values
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onDestroy() {
        super.onDestroy()
        release()
    }
}